package cn.element.leetcode.stage3;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;

/**
 * @description:
 * @author: gonghongwei
 * @create: 2021-11-23 11:58
 */
public class LRUCacheLinkedHashmap {
	private int capacity;
	private LinkedHashMap<Integer, Integer> cache;

	public LRUCacheLinkedHashmap(int capacity, LinkedHashMap<Integer, Integer> cache) {
		this.capacity = capacity;
		this.cache = cache;
	}

	public int get(int key) {
		if (!cache.containsKey(key)) {
			return -1;
		}
		int res = cache.get(key);
		cache.remove(key);
		cache.put(key, res);
		return res;
	}

	public void put(int key, int value) {
		if (cache.containsKey(key)) {
			cache.remove(key); //已经存在，在当前链表移除
		}
		if (capacity == cache.size()){
			//cache已满，删除链表头位置
			Set<Integer> keySet = cache.keySet();
			Iterator<Integer> iterator = keySet.iterator();
			cache.remove(iterator.next());
		}
		cache.put(key,value); //插入到链表末尾
	}


}
